package cn.appsys.controller.devuser;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.appsys.dao.appversion.VersionMapper;
import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.app_category.AppCategoryService;
import cn.appsys.service.datadictionary.DataDictionaryService;
import cn.appsys.service.devuser.AppInfoService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.FileUploadUtil;
import cn.appsys.tools.PageSupport;

@Controller
@RequestMapping(value = "sys/dev/flatform/app")
public class AppInfoController {

	private Logger logger = Logger.getLogger(AppInfoController.class);

	@Resource
	private AppInfoService appInfoService;
	@Resource
	private DataDictionaryService dataDictionaryService;
	@Resource
	private AppCategoryService appCategoryService;
	@Resource
	private VersionMapper versionMapper;
	// 往前面的列表里面传入数据
	List<AppInfo> appInfoList = null;

	/**
	 * 查看app信息列表
	 * 
	 * @param model
	 * @param httpSession
	 * @param querySoftwareName
	 * @param queryStatus
	 * @param queryCategoryLevel1
	 * @param queryCategoryLevel2
	 * @param queryCategoryLevel3
	 * @param queryFlatFormId
	 * @param pageIndex
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String getAppInfoList(Model model, HttpSession httpSession,
			@RequestParam(value = "querySoftwareName", required = false) String querySoftwareName,
			@RequestParam(value = "queryStatus", required = false) String queryStatus,
			@RequestParam(value = "queryCategoryLevel1", required = false) String queryCategoryLevel1,
			@RequestParam(value = "queryCategoryLevel2", required = false) String queryCategoryLevel2,
			@RequestParam(value = "queryCategoryLevel3", required = false) String queryCategoryLevel3,
			@RequestParam(value = "queryFlatformId", required = false) String queryFlatFormId,
			@RequestParam(value = "pageIndex", required = false) String pageIndex) {
		logger.info("getAppInfoList -- > querySoftwareName: " + querySoftwareName);
		logger.info("getAppInfoList -- > queryStatus: " + queryStatus);
		logger.info("getAppInfoList -- > queryCategoryLevel1: " + queryCategoryLevel1);
		logger.info("getAppInfoList -- > queryCategoryLevel2: " + queryCategoryLevel2);
		logger.info("getAppInfoList -- > queryCategoryLevel3: " + queryCategoryLevel3);
		logger.info("getAppInfoList -- > queryFlatformId: " + queryFlatFormId);
		logger.info("getAppInfoList -- > pageIndex: " + pageIndex);
		// 获取当前登录人的信息
		Integer devId = 1;
		// APP状态的下拉列表的取值
		List<DataDictionary> statusList = null;
		// APP所属平台的下拉列表的取值
		List<DataDictionary> flatFormList = null;
		// 列出一级分类列表，注：二级和三级分类类别通过ajax异步获取
		List<AppCategory> categroyLevel1List = null;
		List<AppCategory> categroyLevel2List = null;
		List<AppCategory> categroyLevel3List = null;
		// 页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		Integer currentPageNo = 1;
		if (pageIndex != null) {
			currentPageNo = Integer.valueOf(pageIndex);
		}
		Integer _queryStatus = null;
		if (queryStatus != null && !("").equals(queryStatus)) {
			_queryStatus = Integer.parseInt(queryStatus);
		}
		Integer _queryCategoryLevel1 = null;
		if (queryCategoryLevel1 != null && !queryCategoryLevel1.equals("")) {
			_queryCategoryLevel1 = Integer.parseInt(queryCategoryLevel1);
		}
		Integer _queryCategoryLevel2 = null;
		if (queryCategoryLevel2 != null && !queryCategoryLevel2.equals("")) {
			_queryCategoryLevel2 = Integer.parseInt(queryCategoryLevel2);
		}
		Integer _queryCategoryLevel3 = null;
		if (queryCategoryLevel3 != null && !queryCategoryLevel3.equals("")) {
			_queryCategoryLevel3 = Integer.parseInt(queryCategoryLevel3);
		}
		Integer _queryFlatFormId = null;
		if (queryFlatFormId != null && !queryFlatFormId.equals("")) {
			_queryFlatFormId = Integer.parseInt(queryFlatFormId);
		}

		// 总数量(列表)
		int totalCount = 0;
		try {
			totalCount = appInfoService.getAppInfoCount(querySoftwareName, _queryStatus, _queryCategoryLevel1,
					_queryCategoryLevel2, _queryCategoryLevel3, _queryFlatFormId, devId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		try {
			appInfoList = appInfoService.getAppInfoList(querySoftwareName, _queryStatus, _queryCategoryLevel1,
					_queryCategoryLevel2, _queryCategoryLevel3, _queryFlatFormId, devId, currentPageNo, pageSize);
			statusList = dataDictionaryService.getDataDictionaryList("APP_STATUS");
			flatFormList = dataDictionaryService.getDataDictionaryList("APP_FLATFORM");
			categroyLevel1List = appCategoryService.getAppCategory(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("statusList", statusList);
		model.addAttribute("flatFormList", flatFormList);
		model.addAttribute("categoryLevel1List", categroyLevel1List);
		model.addAttribute("pages", pages);
		model.addAttribute("queryStatus", _queryStatus);
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryCategoryLevel1", _queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", _queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", _queryCategoryLevel3);
		model.addAttribute("queryFlatformId", _queryFlatFormId);

		// 二级分类列表和三级分类列表---回显
		categroyLevel2List = appCategoryService.getAppCategory(_queryCategoryLevel1);
		model.addAttribute("categoryLevel2List", categroyLevel2List);
		categroyLevel3List = appCategoryService.getAppCategory(_queryCategoryLevel2);
		model.addAttribute("categoryLevel3List", categroyLevel3List);

		return "dev/appinfolist";
	}

	/**
	 * 显示一，二，三级分类
	 */
	@RequestMapping(value = "/categorylevellist.json", produces = { "application/json;charset=utf-8" })
	@ResponseBody
	public Object categorylevellist(@RequestParam(value = "pid") Integer id) {
		System.out.println("---------------------------------------------------" + id);
		if(id == null)
			id = 0;
		List<AppCategory> applist = appCategoryService.getAppCategory(id);
		return JSONArray.toJSONString(applist);
	}

	/**
	 * 进入后台app信息查看
	 */
	@RequestMapping(value = "/showAppInfo")
	public String showAppInfo() {
		return "backend/appinfolist";
	}

	/**
	 * 跳转到新增页面
	 */
	@RequestMapping(value = "/appinfoadd")
	public String appinfoadd(@ModelAttribute("AppInfo") AppInfo appinfo) {
		return "dev/appinfoadd";
	}

	/**
	 * 显示所属平台下拉列表
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/datadictionarylist.json", produces = { "application/json;charset=utf-8" })
	@ResponseBody
	public Object datadictionarylist(@RequestParam("tcode") String tcode) throws Exception {
		return JSONArray.toJSONString(dataDictionaryService.getDataDictionaryList(tcode));
	}

	/**
	 * 新增页面点击保存跳到方法
	 */
	@RequestMapping(value = "/appinfoaddsave")
	public String addinfoaddsave(AppInfo appinfo, HttpSession session, HttpServletRequest request,
			@RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach) {
		String logoPicPath = null;
		String logoLocPath = null;
		String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
		String fileName = appinfo.getAPKName() + ".jpg";
		FileUploadUtil fileLoad = new FileUploadUtil(fileName, path, attach, 5000000);
		int falg = fileLoad.upLoadFile();
		if (falg == -1) {
			// 文件过大，上传失败
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
			return "developer/appinfoadd";
		} else if (falg == -2) {
			// 文件格式不正确
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
			return "dev/appinfoadd";
		} else if (falg == -3) {
			// 文件上传失败
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
			return "dev/appinfoadd";
		}
		logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
		logoLocPath = path + File.separator + fileName;
		appinfo.setLogoPicPath(logoPicPath);
		appinfo.setLogoLocPath(logoLocPath);
		appinfo.setCreatedBy(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
		appinfo.setCreationDate(new Date());
		appinfo.setDevId(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
		appinfo.setStatus(1);
		try {
			if (appInfoService.addAppInfo(appinfo)) {
				return "redirect:list";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "developer/appinfoadd";
	}
	@RequestMapping(value = "delapp.json")
	@ResponseBody
	public Object delapp(@RequestParam("id") String appinfoid) {
		HashMap<String, String> map = new HashMap<String, String>();
		if (appInfoService.delAppinfo(Integer.parseInt(appinfoid))) {
			map.put("delResult", "true");
		} else {
			map.put("delResult", "false");
		}
		return JSONObject.toJSONString(map);
	}

	/**
	 * 根据appinfoid获取app信息 存放到model对象中
	 */
	public AppInfo getAppInfo(Integer appId) {
		for (AppInfo appInfo : appInfoList) {
			if (appInfo.getId() == appId)
				return appInfo;
		}
		return null;
	}

	/**
	 * app信息查看
	 */
	@RequestMapping(value = "/appview/{appinfoid}")
	public String appView(@PathVariable Integer appinfoid, Model model) {
		AppInfo appInfo = getAppInfo(appinfoid);
		model.addAttribute("appInfo", appInfo);
		List<AppVersion> appVersionList = versionMapper.getAppVersion(appinfoid);
		model.addAttribute("appVersionList", appVersionList);
		return "dev/appinfoview";
	}

	/**
	 * 修改app信息
	 */
	@RequestMapping(value="/appinfomodify")
	public String appInfomodify(@RequestParam(value = "id") Integer id, Model model) {
		AppInfo appInfo = getAppInfo(id);
		model.addAttribute("appInfo", appInfo);
		return "dev/appinfomodify";
	}

	/**
	 * 修改保存
	 */
	@RequestMapping(value = "/appinfomodifysave")
	public String appInfoModifySave(AppInfo appInfo, HttpSession session,
			@RequestParam(value = "attach", required = false) MultipartFile attach, HttpServletRequest request) {
		String logoPicPath = null;
		String logoLocPath = null;
		String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
		String fileName = appInfo.getAPKName() + ".jpg";
		FileUploadUtil fileLoad = new FileUploadUtil(fileName, path, attach, 5000000);
		int falg = fileLoad.upLoadFile();
		if (falg == -1) {
			// 文件过大，上传失败
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
			return "dev/appinfomodify";
		} else if (falg == -2) {
			// 文件格式不正确
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
			return "dev/appinfomodify";
		} else if (falg == -3) {
			// 文件上传失败
			request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
			return "dev/appinfomodify";
		}
		logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
		logoLocPath = path + File.separator + fileName;
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setModifyBy(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
		appInfo.setModifyDate(new Date());
		if (appInfoService.updateAppInfo(appInfo) > 0)
			return "redirect:/sys/dev/flatform/app/list";
		return "dev/appinfomodifysave";
	}

}
